#!/bin/bash

# 必须配置 jre 系统环境变量，不然无法启动
export LOGBACK_LOG_FILE_ROOT_PATH="/opt/jar/logs"
CURRENT_DATE_TIME=`date "+%Y-%m-%d_%H-%M-%S"`
SERVICE_DIR="/opt/jar"
SERVICE_NAME="cdk8s-jdk11-spring-boot-selenium-jsoup-0.0.1-SNAPSHOT"
JVM_PARAMS="-Xms524m -Xmx524m -Xmn150m -XX:MetaspaceSize=124m -XX:MaxMetaspaceSize=224M"
HEAP_DUMP_PATH="${SERVICE_DIR}/${SERVICE_NAME}_${CURRENT_DATE_TIME}.hprof"
SPRING_PROFILES_ACTIVE=prodgroup

case "$1" in
	start)
		procedure=`ps -ef | grep -w "${SERVICE_NAME}" | grep -v "grep" | awk '{print $2}'`
		if [ "${procedure}" = "" ];
		then
			echo "start ..."
			if [ "$2" != "" ];
			then
				SPRING_PROFILES_ACTIVE=$2
			fi
			echo "spring.profiles.active=${SPRING_PROFILES_ACTIVE}"
			exec nohup java ${JVM_PARAMS} -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${HEAP_DUMP_PATH} -jar ${SERVICE_DIR}/${SERVICE_NAME}\.jar --spring.profiles.active=${SPRING_PROFILES_ACTIVE} > /dev/null 2>&1 &
			procedureCheck=`ps -ef | grep -w "${SERVICE_NAME}" | grep -v "grep" | awk '{print $2}'`
			if [ "${procedureCheck}" = "" ];
			then
				echo "${SERVICE_NAME} start error"
			else
				echo "${SERVICE_NAME} start success"
			fi
		else
			echo "${SERVICE_NAME} is running"
		fi
		;;

	stop)
		procedure=`ps -ef | grep -w "${SERVICE_NAME}" | grep -v "grep" | awk '{print $2}'`
		if [ "${procedure}" = "" ];
		then
			echo "${SERVICE_NAME} is stop"
		else
			# 为了适配 Spring Boot 的优雅关机，这里不能直接使用 kill -9，而是要使用 kill -15
			echo "${SERVICE_NAME} graceful stopping sleep 13s start"
			kill -15 ${procedure}
			# 同时为了等待优雅关机的缓冲时间，这里需要睡眠下。我 timeout-per-shutdown-phase 设置了 10s，所以这里需要稍微睡眠先避免后面的脚本直接执行
			sleep 13
			echo "${SERVICE_NAME} graceful stopping sleep 13s end"
			procedureCheck=`ps -ef | grep -w "${SERVICE_NAME}" | grep -v "grep" | awk '{print $2}'`
			if [ "${procedureCheck}" = "" ];
			then
				echo "${SERVICE_NAME} stop success"
			else
				kill -9 ${procedureCheck}
				echo "${SERVICE_NAME} stop kill -9"
			fi
		fi
		;;

	restart)
		./$0 stop
		sleep 1
		./$0 start $2
		;;

	*)
		echo "usage: $0 [start|stop|restart] [dev|test|prod]"
		;;
esac
